package cn.tedu.socket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class ThreadChatClient {
    private Socket socket;

    public ThreadChatClient() {
        try {
            System.out.println("客户端启动..");
            socket =new Socket("127.0.0.1",8888);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    public  void start(){
        Scanner sc=null;
        PrintWriter pw=null;
        try {
            //1
           pw =new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(), StandardCharsets.UTF_8)), true);
            //2写数据
            sc =new Scanner(System.in);
            System.out.println("请输入数据:");
            while (true) {
                String content = sc.nextLine();
                if ("exit".equalsIgnoreCase(content))break;
                pw.println(content);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //释放资源
            if(pw!=null)pw.close();
            if(sc!=null)sc.close();
            if(socket!=null)try{socket.close();}catch (IOException e){e.printStackTrace();}
        }
    }

    public static void main(String[] args) {
        new ThreadChatClient().start();
    }
}
